


#import "MCouponBViewController.h"
#import "UIViewExt.h"
#import "HttpRequest.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
#import "UIButton+WebCache.h"
#import "TheLoginViewController.h"
#import "UMSocial.h"
#import "MCouponListModel.h"
#import "CouponListCell.h"
#import "MCouponCViewController.h"
#import "CouponBeUsedViewController.h"
@interface MCouponBViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate>

@end

@implementation MCouponBViewController
{
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*modelArray;
    int pageNumber;
    MBProgressHUD *progressHud;
    UITableView *table;
    NSDictionary*Dict;
    NSMutableArray*couponIdArray;
    NSMutableArray*pricesArray;
    UIButton* chooseBtn;
    UIButton* tureBtn;
    UIView*noDataView;
    UIButton*viewBtn;
}
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidDisappear:(BOOL)animated
{   [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    [self addFooter];
    
    [self add];
}
-(void)add{
    [noDataView removeFromSuperview];
    [table removeFromSuperview];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [table registerClass:[CouponListCell class] forCellReuseIdentifier:@"MCouponBViewController"];
    [self.view addSubview:table];
    if ([self.titleName isEqualToString:@"优惠券"]) {
         [self requestData];
    }else{
    
        modelArray=[[NSMutableArray alloc]init];
        couponIdArray=[[NSMutableArray alloc]init];
        pricesArray=[[NSMutableArray alloc]init];
        NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:self.dataDict];
        for (NSDictionary *dic in mItemsArray) {
            
        
            MCouponListModel *dataModel=[MCouponListModel dataModelWithDict:dic];
            [modelArray addObject:dataModel];
            
        }
       
        
        UIView*tableHeader=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        tableHeader.backgroundColor=zuiqianhuiColor;
        table .tableHeaderView=tableHeader;
        UILabel* countLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, 200, 44)];
        countLabel.text=[NSString stringWithFormat:@"共 %ld 张",(unsigned long)modelArray.count];
        countLabel.textColor=shenhuiColor;
        countLabel.font=[UIFont systemFontOfSize:15];
        [tableHeader addSubview:countLabel];
        UIImage *img=[UIImage imageNamed:@"qingkong"];
        UIImage *tinted = [img rt_tintedImageWithColor:shenhuiColor];
        UIButton*sxBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-40, 6.5, 30, 30)];
        [sxBtn setImage:tinted forState:UIControlStateNormal];
        [sxBtn addTarget:self action:@selector(qingkong:) forControlEvents:UIControlEventTouchUpInside];
        [tableHeader addSubview:sxBtn];
        [table reloadData];
        [tureBtn removeFromSuperview];
        tureBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight-48,ScreenWidth, 48)];
        [tureBtn setTitle:@"确定核销" forState:UIControlStateNormal];
        tureBtn.backgroundColor=luseColor;
        [tureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        tureBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [tureBtn addTarget:self action:@selector(tureBtn1:) forControlEvents:UIControlEventTouchUpInside];
        tureBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [self.view addSubview:tureBtn];
        
        if (self.dataDict.count>0) {
            [noDataView removeFromSuperview];
        }else{
            
           
            
            noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
            [self.view addSubview:noDataView];
            UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
            noImage.image=[UIImage imageNamed:@"meiyoushuju"];
            [noDataView addSubview:noImage];
            UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
            noLabel.text=@"没有列表数据，赶紧去添加！";
            noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
            noLabel.textAlignment=NSTextAlignmentCenter;
            [noDataView addSubview:noLabel];

            
            tureBtn.backgroundColor=qianhuiColor;
            tureBtn.userInteractionEnabled=NO;
        }

    }
}

-(void)qingkong:(UIButton*)sender{
    UIAlertView* alts = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"确定要清空？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    alts.tag=0;
    [alts show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==0) {
        if (buttonIndex == 0) {
            
        }else{
            [self.dataDict removeAllObjects];
            [self add];
            [_mDelegate update:@""];

        }
    }else{
        if (buttonIndex == 0) {
           
        }else{
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        [param setValue:self.snList forKey:@"snList"];
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:20 view:self.view];
        [HttpRequest requestData:@"Business/Coupon/BeUsed" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                
                NSLog(@"====%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    
                    [Global hideProgressHUDInternal:self.view];
                    [self showAlertMessage:@"核销成功！"];
                    [self.dataDict removeAllObjects];
                    [self add];
                    [_mDelegate update:@""];
                }else{
                
                    [Global hideProgressHUDInternal:self.view];
                    
                    [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];
                }
                
            }
            
            else
            {
                [Global hideProgressHUDInternal:self.view];
                
                [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];
            }
            
        }];
        
 
    }
    }
    
}
-(void)tureBtn1:(UIButton*)sender{

    UIAlertView* alts = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"确定要核销？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    alts.tag=1;
    [alts show];

}
-(void)requestData{
    modelArray=[[NSMutableArray alloc]init];
    couponIdArray=[[NSMutableArray alloc]init];
    pricesArray=[[NSMutableArray alloc]init];
    pageNumber = 1;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:self.memberId forKey:@"memberId"];
    [param setValue:@"1" forKey:@"searchType"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:20 view:self.view];
    [HttpRequest requestData:@"Business/MCoupon/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                NSString*TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                if (TotalCount.intValue==0) {
                    noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                    [self.view addSubview:noDataView];
                    UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                    noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                    [noDataView addSubview:noImage];
                    UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                    noLabel.text=@"没有列表数据，赶紧去添加！";
                    noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                    noLabel.textAlignment=NSTextAlignmentCenter;
                    [noDataView addSubview:noLabel];
                }else{
                    NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                    for (NSDictionary *dic in mItemsArray) {
                        MCouponListModel *dataModel=[MCouponListModel dataModelWithDict:dic];
                        [modelArray addObject:dataModel];
                        
                    }
                    [table reloadData];
                }
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
    
}


//上拉刷新
- (void)addFooter
{
    
    
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:3.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
    
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [table reloadData];
    [refreshView endRefreshing];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [modelArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CouponListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MCouponBViewController"];
    cell.index=[NSString stringWithFormat:@"%ld", (long)indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.MCouponListModel=modelArray[indexPath.row];
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    
    if ([self.titleName isEqualToString:@"优惠券"]) {
    MCouponListModel *ScreeningModel=modelArray[indexPath.row];
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    CouponListCell *sharecell=(CouponListCell *)cell;
    sharecell.saveAccount=! sharecell.saveAccount;
    
    if (!sharecell.saveAccount) {
        [couponIdArray addObject:[NSString stringWithFormat:@"%@",ScreeningModel.sn]];
        [pricesArray addObject:[NSString stringWithFormat:@"%@",ScreeningModel.price]];
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        CouponListCell *sharecell=(CouponListCell *)cell;
        [sharecell.share setBackgroundImage:[UIImage imageNamed:@"gouxuan"] forState:UIControlStateNormal];
        ScreeningModel.isUsed=@"1";
        [modelArray replaceObjectAtIndex:indexPath.row withObject:ScreeningModel];
        [self addTabar:pricesArray];
      
    }
    else{
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        CouponListCell *sharecell=(CouponListCell *)cell;
        [sharecell.share setBackgroundImage:[UIImage imageNamed: @""] forState:UIControlStateNormal];
        ScreeningModel.isUsed=@"0";
        [modelArray replaceObjectAtIndex:indexPath.row withObject:ScreeningModel];
        if (couponIdArray.count>0) {
            
            for (int i=0; i<couponIdArray.count; i++) {
                
                NSString *codeStr = [couponIdArray objectAtIndex:i];
                if ([codeStr isEqualToString:[NSString stringWithFormat:@"%@",ScreeningModel.sn]] ) {
                    [pricesArray removeObjectAtIndex:i];//从指定索引移除
                    [couponIdArray removeObjectAtIndex:i];//从指定索引移除
                
                }
                    [self addTabar:pricesArray];
             

            }
        }
    }

    }else{
    
    
    
    }


}
-(void)addTabar:(NSMutableArray*)discountAmount{
    if (couponIdArray.count>0) {
        
        [viewBtn removeFromSuperview];
        [tureBtn removeFromSuperview];
        double d1;
        NSNumber *sum = [pricesArray valueForKeyPath:@"@sum.floatValue"];
        d1=sum.doubleValue;
        
        
       viewBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight-48,ScreenWidth-160, 48)];
        viewBtn.backgroundColor=[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
        viewBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        [viewBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        viewBtn.alpha=0.8;
        [self.view addSubview:viewBtn];
       
        UIButton*totalPriceLabel=[[UIButton alloc]initWithFrame:CGRectMake(0, 0,ScreenWidth-160, 30)];
        totalPriceLabel.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        [totalPriceLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [totalPriceLabel setTitle:[NSString stringWithFormat:@"    已选 %ld 件",(unsigned long)pricesArray.count] forState:UIControlStateNormal];
        totalPriceLabel.titleLabel.font=[UIFont systemFontOfSize:10];
        [viewBtn addSubview:totalPriceLabel];

        chooseBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 18, ScreenWidth-160, 30)];
        [chooseBtn setTitle:[NSString stringWithFormat:@"   合计 ¥ %@",[NSString stringWithFormat:@"%.2f",d1]] forState:UIControlStateNormal];
        [chooseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        chooseBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
        chooseBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [viewBtn addSubview:chooseBtn];
        
        tureBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-160, ScreenHeight-48,160, 48)];
        [tureBtn setTitle:@"确定核销" forState:UIControlStateNormal];
        tureBtn.backgroundColor=luseColor;
        [tureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        tureBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [tureBtn addTarget:self action:@selector(tureBtn:) forControlEvents:UIControlEventTouchUpInside];
        tureBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [self.view addSubview:tureBtn];
        
    }else{
         [viewBtn removeFromSuperview];
        [chooseBtn removeFromSuperview];
        [tureBtn removeFromSuperview];
    }
    
}


- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    self.title=self.titleName;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
   
    if ([self.titleName isEqualToString:@"优惠券"]) {
        UIButton*historicalRecord = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0, 65, 25)];
        [historicalRecord setTitle:@"历史记录" forState:UIControlStateNormal];
        [historicalRecord setTitleColor:shenhuiColor forState:UIControlStateNormal];
        historicalRecord.titleLabel.font=[UIFont systemFontOfSize:12];
        [historicalRecord addTarget:self action:@selector(historicalRecord:) forControlEvents:UIControlEventTouchUpInside];
        [historicalRecord.layer setCornerRadius:0]; //设置矩圆角半径
        [historicalRecord.layer setBorderWidth:0.3];   //边框宽度
        CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
        CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){204/255.0, 204/255.0, 204/255.0, 1.0});
        [historicalRecord.layer setBorderColor:tureBTncolorref];//边框颜色
        UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:historicalRecord];
        self.navigationItem.rightBarButtonItem = myBtnBtn;

    }
    
   
    
}


-(void)tureBtn:(UIButton*)sender{
    
    CouponBeUsedViewController *detailViewController = [[CouponBeUsedViewController alloc] init];
    detailViewController.phone=self.phone;
    detailViewController.snList=couponIdArray;
    [self.navigationController pushViewController:detailViewController animated:YES];
}
-(void)historicalRecord:(UIButton*)sender{

    MCouponCViewController *detailViewController = [[MCouponCViewController alloc] init];
    detailViewController.memberId=self.memberId;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

@end
